//
//  CYPublishVideoViewController.m
//  cyydt
//
//  Created by chu on 2019/1/19.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYPublishVideoViewController.h"

#import <Masonry.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UtilMacro.h"
#import "MMFileUploadUtil.h"
#import "MMRichContentUtil.h"

#import "MMRichTextConfig.h"
#import "MMDraftUtil.h"

#import "MMRichTitleModel.h"
#import "MMRichTextModel.h"
#import "MMDraftModel.h"

#import "MMRichTitleCell.h"
#import "MMRichTextCell.h"

#import "UIView+JCAddition.h"

#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>

#define bottomOffsetHeight                  convertLength(49)

@interface CYPublishVideoViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, RichTextEditArcDelegate>


@property (nonatomic, strong) UIButton *selVideoBtn;
@property (nonatomic, strong) UIImageView *bofanImg;
@property (nonatomic, copy) NSString *videoFullPath;
@property (nonatomic, strong) CYCategrayModel *selBigCateModel;
@property (nonatomic, strong) CYCategrayModel *selSmallCateModel;
@property (nonatomic, strong) UIButton *labelBtn;

@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) UIView *refreshBackView;
@property (nonatomic, strong) UILabel *refreshTipLabel;

@property (nonatomic, strong) UIView *editToolbar;

@property (nonatomic, strong) MMRichTitleModel* titleModel;
@property (nonatomic, strong) NSMutableArray* datas;
@property (nonatomic, strong) NSIndexPath* activeIndexPath;

@property (nonatomic, copy) NSString* tid;///<论坛ID
@property (nonatomic, strong) MMDraftModel* draft;

@property (nonatomic, assign) BOOL isOnUploading;

@property (nonatomic, strong) UIView *bottomView;

@property (strong, nonatomic) HXPhotoManager *manager;
@property (nonatomic, strong) NSMutableArray* categaryArr;
@property (nonatomic, strong) CYProjectModel *detailModel;

@end

@implementation CYPublishVideoViewController

- (instancetype)initWithTid:(NSString*)tid {
    self = [super init];
    if (self) {
        _tid = tid;
    }
    return self;
}

- (instancetype)initWithDraft:(MMDraftModel*)draft {
    self = [super init];
    if (self) {
        _tid = draft.tid;
        _draft = draft;
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"发布视频";
    [self rightBarItemWithTitle:@"发布"];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);

    }];
    [self.view addSubview:self.refreshBackView];
    
    
    // register cell
    [self.tableView registerClass:MMRichTitleCell.class forCellReuseIdentifier:NSStringFromClass(MMRichTitleCell.class)];
    [self.tableView registerClass:MMRichTextCell.class forCellReuseIdentifier:NSStringFromClass(MMRichTextCell.class)];
    
    // Datas
    if (_draft) {
        if ((MMRichTitleModel*)_draft.titleModel) {
            _titleModel = (MMRichTitleModel*)_draft.titleModel;
        } else {
            _titleModel = [MMRichTitleModel new];
        }
        _datas = [NSMutableArray array];
        if (_draft.contentModels) {
            [_datas addObjectsFromArray:_draft.contentModels];
        } else {
            [_datas addObject:[MMRichTextModel new]];
        }
    } else {
        _titleModel = [MMRichTitleModel new];
        _datas = [NSMutableArray array];
        [_datas addObject:[MMRichTextModel new]];
    }
    
    // Notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self getAllCategary];
    if (self.questionId) {
        [self getDetail];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [UITableView new];
        _tableView.backgroundColor = BackGroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //        tableView.estimatedRowHeight = 200;
        //        tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTableViewTap)]];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, bottomOffsetHeight, 0);
        _tableView.tableFooterView = self.bottomView;
    }
    return _tableView;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    NSLog(@"===dealloc===");
}

- (void)handleInsertImage:(UIImage*)image {
    
    if (!_activeIndexPath) {
        _activeIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    }
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:_activeIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 处理文本节点
        // 根据光标拆分文本节点
        BOOL isPre = NO;
        BOOL isPost = NO;
        NSArray* splitedTexts = [((MMRichTextCell*)cell) splitedTextArrWithPreFlag:&isPre postFlag:&isPost];
        
        // 前面优先级更高，需要调整优先级，调整if语句的位置即可
        if (isPre) {
            // 前面添加图片，光标停留在当前位置
            [self addImageNodeAtIndexPath:_activeIndexPath image:image];
            [self postHandleAddImageNode:_activeIndexPath];
        } else if (isPost) {
            // 后面添加图片，光标移动到下一行
            NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:_activeIndexPath.row + 1 inSection:_activeIndexPath.section];
            [self addImageNodeAtIndexPath:nextIndexPath image:image];
            [self postHandleAddImageNode:nextIndexPath];
        } else {
            // 替换当前节点，添加Text/image/Text，光标移动到图片节点上
            NSInteger tmpActiveIndexRow = _activeIndexPath.row;
            NSInteger tmpActiveIndexSection = _activeIndexPath.section;
            [self deleteItemAtIndexPath:_activeIndexPath shouldPositionPrevious:NO];
            if (splitedTexts.count == 2) {
                // 第一段文字
                [self addTextNodeAtIndexPath:_activeIndexPath textContent:[splitedTexts.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                // 图片
                [self addImageNodeAtIndexPath:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection] image:image];
                // 第二段文字
                [self addTextNodeAtIndexPath:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 2 inSection:_activeIndexPath.section] textContent:[splitedTexts.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
                // 光标移动到图片位置
                [self positionAtIndex:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection]];
                [self postHandleAddImageNode:[NSIndexPath indexPathForRow:tmpActiveIndexRow + 1 inSection:tmpActiveIndexSection]];
            }
        }
        
    } else {
        
    }
}


#pragma mark backbtntap

- (void)backButtonTapped {
    // 保存草稿箱
    if (_draft) {
        if ([MMRichContentUtil validateTitle:_titleModel]
            || [MMRichContentUtil validataContentNotEmptyWithRichContents:_datas]) {
            MMDraftModel* draftData = [MMDraftUtil draftModelWithTitleModel:_titleModel contents:_datas tid:_tid draftId:_draft.draftId];
            [MMDraftUtil saveDraftData:draftData];
        } else {
            // 删除草稿箱
            [MMDraftUtil delateDraftData:_draft];
        }
    } else {
        if ([MMRichContentUtil validateTitle:_titleModel]
            || [MMRichContentUtil validataContentNotEmptyWithRichContents:_datas]) {
            MMDraftModel* draftData = [MMDraftUtil draftModelWithTitleModel:_titleModel contents:_datas tid:_tid draftId:0];
            [MMDraftUtil saveDraftData:draftData];
        }
    }
    
    [[AppDelegate sharedAppDelegate] popViewController];
}


#pragma mark - ......::::::: ui actoin :::::::......

- (void)RighttouchEvent {
    [self.view endEditing:YES];
    // 验证输入
    // 1、验证内容
    if (![MMRichContentUtil validataContentNotEmptyWithRichContents:_datas]) {
        [self.view makeToast:@"视频正文不能小于20个字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 2、验证title
    if (![MMRichContentUtil validateTitle:_titleModel]) {
        [self.view makeToast:@"视频标题不能小于3个字大于20个字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 3、验证内容是否超过上限
    if (![MMRichContentUtil validataContentNotOverflowWithRichContents:_datas]) {
        [self.view makeToast:@"视频正文不能大于500字" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 4、验证图片时候上传成功
    if (![MMRichContentUtil validateImagesWithRichContents:self.datas]) {
        // 还有图片没上传或者图片失败的情况
        return;
    }
    
    if ([NSString stringIsNull:self.videoFullPath]) {
        [self.view makeToast:@"请上传您的视频" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    
    // 发送内容
    _isOnUploading = YES;
    NSMutableString *muStr = [NSMutableString string];
    NSMutableArray *muArr = [NSMutableArray arrayWithCapacity:0];
    for (id model in self.datas) {
        if ([model isKindOfClass:[MMRichTextModel class]]) {
            MMRichTextModel *text = (MMRichTextModel *)model;
            NSLog(@"text.textContent - %@", text.textContent);
            if (![NSString stringIsNull:text.textContent]) {
                [muStr appendString:[NSString stringWithFormat:@"%@",text.textContent]];
                [muArr addObject:text.textContent];
            }
            
        }
    }
    [self add_articleWithTitle:_titleModel.textContent TempContent:muStr];
}

- (void)add_articleWithTitle:(NSString *)title TempContent:(NSString *)tempContent{
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"video"];
    NSNumber *subCategory = @28;
    if (self.selBigCateModel) {
        subCategory = self.selBigCateModel.catid;
    }
    NSDictionary *param = @{};
    if (self.questionId) {
        param = @{@"id":self.questionId, @"title":title, @"content":tempContent, @"subCategory":subCategory, @"source":@6, @"url":self.videoFullPath};
    }else{
        param = @{@"title":title, @"content":tempContent, @"subCategory":subCategory, @"source":@6, @"url":self.videoFullPath};
    }
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"发布文章 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [[AppDelegate sharedAppDelegate] popViewController];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
    
}

- (void)onTableViewTap {
    NSIndexPath* lastIndexPath = [NSIndexPath indexPathForRow:_datas.count - 1 inSection:1];
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        [((MMRichTextCell*)cell) mm_beginEditing];
    }
}


#pragma mark - Node Handler

- (void)addImageNodeAtIndexPath:(NSIndexPath*)indexPath image:(UIImage*)image {
    
}

- (void)postHandleAddImageNode:(NSIndexPath*)indexPath {
    if (indexPath.row < _datas.count - 1) {
        NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        id nextData = _datas[nextIndexPath.row];
        if ([nextData isKindOfClass:[MMRichTextModel class]]) {
            // Image节点-后面：下面是text，光标移动到下面一行，并且在最前面添加一个换行，定位光标在最前面
            [self.tableView scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
            MMRichTextModel* textModel = ((MMRichTextModel*)nextData);
            textModel.selectedRange = NSMakeRange(0, 0);
            textModel.shouldUpdateSelectedRange = YES;
            [self positionAtIndex:nextIndexPath];
            
        }
    } else {
        // 添加文字到下一行
        NSIndexPath* nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        [self addTextNodeAtIndexPath:nextIndexPath textContent:@""];
    }
}

- (void)addTextNodeAtIndexPath:(NSIndexPath*)indexPath textContent:(NSString*)textContent {
    MMRichTextModel* textModel = [MMRichTextModel new];
    textModel.textContent = [textContent isEqualToString:@"\n"] ? @"" : textContent == nil ? @"" : textContent;
    textModel.textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:textModel.textContent];
    
    [self.tableView beginUpdates];
    [_datas insertObject:textModel atIndex:indexPath.row];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    [self.tableView endUpdates];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    
    // 定位到新增的元素
    [self positionAtIndex:indexPath];
}

- (void)deleteItemAtIndexPathes:(NSArray<NSIndexPath*>*)actionIndexPathes shouldPositionPrevious:(BOOL)shouldPositionPrevious {
    if (actionIndexPathes.count > 0) {
        // 处理删除
        for (NSInteger i = actionIndexPathes.count - 1; i >= 0; i--) {
            NSIndexPath* actionIndexPath = actionIndexPathes[i];
            [_datas removeObjectAtIndex:actionIndexPath.row];
        }
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:actionIndexPathes withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
        
        //  定位动到上一行
        if (shouldPositionPrevious) {
            [self positionToPreItemAtIndexPath:actionIndexPathes.firstObject];
        }
    }
}

- (void)deleteItemAtIndexPath:(NSIndexPath*)actionIndexPath shouldPositionPrevious:(BOOL)shouldPositionPrevious {
    //  定位动到上一行
    if (shouldPositionPrevious) {
        [self positionToPreItemAtIndexPath:actionIndexPath];
    }
    
    // 处理删除
    [_datas removeObjectAtIndex:actionIndexPath.row];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:actionIndexPath.row inSection:actionIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
}

/**
 定位到指定的元素
 */
- (void)positionAtIndex:(NSIndexPath*)indexPath {
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        [((MMRichTextCell*)cell) mm_beginEditing];
    }
}

// 定位动到上一行
- (void)positionToPreItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    NSIndexPath* preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row - 1 inSection:actionIndexPath.section];
    [self positionAtIndex:preIndexPath];
}

// 定位动到上一行
- (void)positionToNextItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    NSIndexPath* preIndexPath = [NSIndexPath indexPathForRow:actionIndexPath.row + 1 inSection:actionIndexPath.section];
    [self positionAtIndex:preIndexPath];
}



#pragma mark - ......::::::: UIImagePickerController :::::::......

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage* image = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^ {
        // 模拟插入多图，插入多图只要多次调用 handleInsertImage 即可
        //        for (int i = 0; i < 2; i++) {
        //            [self handleInsertImage:image];
        //        }
        
        // 插入单图
        [self handleInsertImage:image];
    }];
}


#pragma mark - ......::::::: RichTextEditDelegate :::::::......

- (void)mm_preInsertTextLineAtIndexPath:(NSIndexPath*)actionIndexPath textContent:(NSString*)textContent {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
    }
}

- (void)mm_postInsertTextLineAtIndexPath:(NSIndexPath*)actionIndexPath textContent:(NSString *)textContent {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
    }
}

- (void)mm_preDeleteItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 处理Text节点
        if (actionIndexPath.row < _datas.count) {
            
            if (actionIndexPath.row <= 0) {
                MMRichTextModel* textModel = (MMRichTextModel*)_datas[actionIndexPath.row];
                if (_datas.count == 1) {
                    // Text节点-当前的Text为空-前面-没有其他元素-：不处理
                    // Text节点-当前的Text不为空-前面-没有其他元素-：不处理
                } else {
                    if (textModel.textContent.length == 0) {
                        // Text节点-当前的Text为空-前面-有其他元素-：删除这一行，定位光标到下面图片的最后
                        [self positionToNextItemAtIndexPath:actionIndexPath];
                        [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:NO];
                    } else {
                        // Text节点-当前的Text不为空-前面-有其他元素-：不处理
                    }
                }
            } else {
                MMRichTextModel* textModel = (MMRichTextModel*)_datas[actionIndexPath.row];
                if (textModel.textContent.length == 0) {
                    // Text节点-当前的Text为空-前面-有其他元素-：删除这一行，定位光标到上面图片的最后
                    [self deleteItemAtIndexPath:actionIndexPath shouldPositionPrevious:YES];
                    
                } else {
                    // 当前节点不为空
                    // Text节点-当前的Text不为空-前面-：上面是图片，定位光标到上面图片的最后
                    // Text节点不存在相邻的情况，所以直接定位上上一个元素即可
                    [self positionToPreItemAtIndexPath:actionIndexPath];
                }
            }
        }
    }
}

- (void)mm_PostDeleteItemAtIndexPath:(NSIndexPath*)actionIndexPath {
    
    UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:actionIndexPath];
    if ([cell isKindOfClass:[MMRichTextCell class]]) {
        // 不处理
        // Text节点-当前的Text不为空-后面-：正常删除
        // Text节点-当前的Text为空-后面-：正常删除，和第三种情况：为空的情况处理一样
    }
}

// 更新ActionIndexpath
- (void)mm_updateActiveIndexPath:(NSIndexPath*)activeIndexPath {
    _activeIndexPath = activeIndexPath;
    NSLog(@"mm_updateActiveIndexPath ===== %@", activeIndexPath);
}

// 重新加载
- (void)mm_reloadItemAtIndexPath:(NSIndexPath*)actionIndexPath {
//    [self handleReloadItemAdIndexPath:actionIndexPath];
}

- (void)mm_uploadFailedAtIndexPath:(NSIndexPath *)actionIndexPath {
}

- (void)mm_uploadDonedAtIndexPath:(NSIndexPath *)actionIndexPath {
}

- (BOOL)mm_shouldCellShowPlaceholder {
    return [MMRichContentUtil shouldShowPlaceHolderFromRichContents:_datas];
}

- (void)mm_shouldShowAccessoryView:(BOOL)shouldShow {
    
}



#pragma mark - ......::::::: MMRichEditAccessoryViewDelegate :::::::......

- (void)mm_didKeyboardTapInaccessoryView:(MMRichEditAccessoryView *)accessoryView {
    [self.view endEditing:YES];
}

- (void)mm_didImageTapInaccessoryView:(MMRichEditAccessoryView *)accessoryView {

}


#pragma mark - ......::::::: Notification :::::::......

- (void)keyboardWillChangeFrame:(NSNotification*)noti {
    
    CGRect keyboardFrame = [noti.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    NSTimeInterval keyboardAnimTime = [noti.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    CGFloat keyboardH = kScreenHeight - keyboardFrame.origin.y;
    if (keyboardH > 50) {
        // 处理显示AccessorityView
        [UIView animateWithDuration:keyboardAnimTime animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, bottomOffsetHeight, 0);
            
            [self.view layoutIfNeeded];
        }];
    } else {
        // 处理隐藏AccessorityView
        [UIView animateWithDuration:keyboardAnimTime animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, 0, bottomOffsetHeight, 0);
            [self.view layoutIfNeeded];
        }];
    }
    [UIView animateWithDuration:keyboardAnimTime animations:^{
        [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-keyboardH);
        }];
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - ......::::::: UITableView Handler :::::::......

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Title
    if (section == 0) {
        return 1;
    }
    // Content
    return _datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return _titleModel.cellHeight;
    } else if (indexPath.section == 1) {
        id obj = _datas[indexPath.row];
        if ([obj isKindOfClass:[MMRichTextModel class]]) {
            MMRichTextModel* textModel = (MMRichTextModel*)obj;
            return textModel.textContentHeight;
        }
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Title
    if (indexPath.section == 0) {
        MMRichTitleCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MMRichTitleCell.class)];
        cell.delegate = self;
        [cell updateWithData:_titleModel indexPath:indexPath];
        return cell;
    }
    // Content
    id obj = _datas[indexPath.row];
    if ([obj isKindOfClass:[MMRichTextModel class]]) {
        MMRichTextCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(MMRichTextCell.class)];
        cell.delegate = self;
        [cell updateWithData:obj indexPath:indexPath];
        return cell;
    }

    
    static NSString* cellID = @"cellId";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark - 底部选择标签视图
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWindowW, 195)];
        _bottomView.backgroundColor = BackGroundColor;
        
        UIView *upView = [[UIView alloc] init];
        upView.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:upView];
        [upView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.top.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.right.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.height.mas_equalTo(80);
        }];
        
        UIButton *addVideo = [UIButton buttonWithType:UIButtonTypeCustom];
        self.selVideoBtn = addVideo;
        [addVideo setTitle:@"+" forState:UIControlStateNormal];
        [addVideo setTitleColor:RGBOF(0x999999) forState:UIControlStateNormal];
        addVideo.titleLabel.font = [UIFont systemFontOfSize:22];
        addVideo.layer.cornerRadius = 5;
        addVideo.layer.masksToBounds = YES;
        addVideo.layer.borderWidth = 1;
        addVideo.layer.borderColor = RGBOF(0xe3e3e3).CGColor;
        [upView addSubview:addVideo];
        [addVideo addTarget:self action:@selector(addVideo:) forControlEvents:UIControlEventTouchUpInside];
        [addVideo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(upView).with.mas_equalTo(15);
            make.top.equalTo(upView).with.mas_equalTo(15);
            make.height.mas_equalTo(60);
            make.width.mas_equalTo(60);
        }];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zpgl_bf"]];
        self.bofanImg = imageView;
        imageView.hidden = YES;
        [addVideo addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(addVideo).with.mas_equalTo(19);
            make.top.equalTo(addVideo).with.mas_equalTo(19);
            make.height.mas_equalTo(22);
            make.width.mas_equalTo(22);
        }];
        
        
        
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.top.equalTo(upView.mas_bottom).with.mas_equalTo(15);
            make.right.equalTo(self->_bottomView).with.mas_equalTo(0);
            make.height.mas_equalTo(100);
        }];
        
        UILabel *label = [[UILabel alloc] init];
        [view addSubview:label];
        label.text = @"选择行业";
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = RGBOF(0x666666);
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).with.mas_equalTo(15);
            make.top.equalTo(view).with.mas_equalTo(15);
            make.right.equalTo(view).with.mas_equalTo(-15);
            
        }];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.labelBtn = btn;
        [btn setTitle:@"+ 添加" forState:UIControlStateNormal];
        [btn setTitleColor:RGBOF(0x97A2B9) forState:UIControlStateNormal];
        [btn setBackgroundColor:RGBOF(0xF4F5FA)];        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setContentEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 25)];
        btn.layer.cornerRadius = 15;
        btn.layer.masksToBounds = YES;
//        btn.layer.borderWidth = 1;
//        btn.layer.borderColor = RGBOF(0xe3e3e3).CGColor;
        [view addSubview:btn];
        [btn addTarget:self action:@selector(showlabel:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).with.mas_equalTo(15);
            make.top.equalTo(label.mas_bottom).with.mas_equalTo(15);
            make.height.mas_equalTo(30);
        }];
    }
    return _bottomView;
}

#pragma mark - 获取所有分类
- (void)getAllCategary{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"categories"];
    NSDictionary *param = @{@"type":@28};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取所有分类 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *data = responseResult[@"data"];
                    [self.categaryArr removeAllObjects];
                    for (NSDictionary *dic in data) {
                        NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                        [muDic setObject:dic[@"name"] forKey:@"catname"];
                        [muDic setObject:dic[@"id"] forKey:@"catid"];
                        [muDic setObject:dic[@"childCates"] forKey:@"child"];
                        [muDic removeObjectForKey:@"id"];
                        [muDic removeObjectForKey:@"name"];
                        [muDic removeObjectForKey:@"childCates"];
                        CYCategrayModel *model = [CYCategrayModel modelWithDictionary:muDic];
                        [self.categaryArr addObject:model];
                    }
                    if (self.detailModel) {
                        [self initCate];
                    }
                }
            }else{
                
            }
        }
    }];
}

#pragma mark - 获取视频详情
- (void)getDetail{
    NSString *url = [NSString stringWithFormat:@"%@%@/%@",User_HOST, @"video", self.questionId];
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:nil ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取视频详情 ---- %@",responseResult);
        
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    self.detailModel = [CYProjectModel mj_objectWithKeyValues:data];
                    [self machiningDataWithDic:data];
                }
            }else{
                [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)initCate{
    for (CYCategrayModel *bigCate in self.categaryArr) {
        if ([bigCate.catid integerValue] == [self.detailModel.category integerValue]) {
            self.selBigCateModel = bigCate;
            for (CYCategrayModel *smallCate in bigCate.child) {
                if ([smallCate.catid integerValue] == [self.detailModel.subCategory integerValue]){
                    self.selSmallCateModel = smallCate;
                }
            }
        }
    }
    if (self.selBigCateModel) {
        if (self.selSmallCateModel) {
            [self.labelBtn setTitle:[NSString stringWithFormat:@"%@-%@",self.selBigCateModel.catname, self.selSmallCateModel.catname] forState:UIControlStateNormal];
        }else{
            [self.labelBtn setTitle:[NSString stringWithFormat:@"%@",self.selBigCateModel.catname] forState:UIControlStateNormal];
        }
        [self.view layoutIfNeeded];
        [self addDelBtn];
    }else{
        [self.labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    }
}

#pragma mark - 获取文章详情后 对返回数据加工处理
- (void)machiningDataWithDic:(NSDictionary *)dic{
    if (dic.count > 0) {
        //获取第一帧图片
        UIImage *image = [self getVideoPreViewImage:[NSURL URLWithString:dic[@"fullurl"]]];
        [self.selVideoBtn setImage:image forState:UIControlStateNormal];
        self.videoFullPath = dic[@"url"];
        self.titleModel.textContent = dic[@"title"];
        NSString *content = dic[@"content"];
        _datas = [NSMutableArray array];
        MMRichTextModel *text = [MMRichTextModel new];
        text.textContent = content;
        text.textContentHeight = [MMRichContentUtil computeHeightInTextVIewWithContent:content];
        text.selectedRange = NSMakeRange(content.length, 0);
        text.shouldUpdateSelectedRange = YES;
        [_datas addObject:text];

        UIImage *coverImage = [self getVideoPreViewImage:[NSURL URLWithString:dic[@"fullurl"]]];
        [self.selVideoBtn setImage:coverImage forState:UIControlStateNormal];
        self.bofanImg.hidden = NO;
        [self.tableView reloadData];

    }
    if (self.categaryArr.count > 0) {
        [self initCate];
    }
}

- (void)showlabel:(UIButton *)sender{
    [self.view endEditing:YES];
    NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYSelCategaryView" owner:self options:nil];
    CYSelCategaryView *backView = [nibView objectAtIndex:0];
    backView.frame = CGRectMake(0, 0, kWindowW, 410);
    backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    backView.dataSourceArr = self.categaryArr;
    backView.haveSmallCategary = NO;
    __weak typeof(self)weakself = self;
    backView.block = ^(CYCategrayModel * _Nonnull bigCateModel, CYCategrayModel * _Nonnull smallCateModel) {
        weakself.selBigCateModel = bigCateModel;
        weakself.selSmallCateModel = smallCateModel;
        if (bigCateModel) {
            if (smallCateModel) {
                [weakself.labelBtn setTitle:[NSString stringWithFormat:@"%@-%@",bigCateModel.catname, smallCateModel.catname] forState:UIControlStateNormal];
            }else{
                [weakself.labelBtn setTitle:[NSString stringWithFormat:@"%@",bigCateModel.catname] forState:UIControlStateNormal];
            }
            [weakself.view layoutIfNeeded];
            [weakself addDelBtn];
        }else{
            [weakself.labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
        }
    };
    [GKCover translucentCoverFrom:[UIApplication sharedApplication].keyWindow content:backView animated:YES showBlock:^{
        // 显示出来时的block
        NSLog(@"弹窗显示了，6不6");
    } hideBlock:^{
        // 移除后的block
        NSLog(@"弹窗消失了，555");
    }];
}

- (void)addDelBtn{
    for (UIView *view in self.bottomView.subviews) {
        if (view.tag == 10033) {
            [view removeFromSuperview];
        }
    }
    UIButton *btn = [[UIButton alloc] init];
    btn.tag = 10033;
    [btn setImage:[UIImage imageNamed:@"ss_gb"] forState:UIControlStateNormal];
    [self.bottomView addSubview:btn];
    [btn addTarget:self action:@selector(delCate:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat marginLeft = self.labelBtn.frame.size.width + 7;
    __weak typeof(self)weakself = self;
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(14);
        make.height.mas_equalTo(14);
        make.left.equalTo(weakself.bottomView).with.mas_equalTo(marginLeft);
        make.bottom.equalTo(weakself.bottomView).with.mas_equalTo(-45);
    }];
}

- (void)delCate:(UIButton *)sender{
    [self.labelBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    self.selBigCateModel = nil;
    self.selSmallCateModel = nil;
    [sender removeFromSuperview];
}

- (void)addVideo:(UIButton *)sender{
    __weak typeof(self)weakself = self;
    [LEEAlert actionsheet].config
    .LeeTitle(@"视频录制")         // 添加一个标题 (默认样式)
    .LeeAction(@"相册", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
        // 点击事件Block
        [weakself hx_presentSelectPhotoControllerWithManager:weakself.manager didDone:^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL isOriginal, UIViewController *viewController, HXPhotoManager *manager) {
            [UINavigationBar appearance].translucent = NO;

            NSLog(@"block - all - %@",allList);
            NSLog(@"block - photo - %@",photoList);
            NSLog(@"block - video - %@",videoList);
            if (videoList.count > 0) {
                HXPhotoModel *model = [videoList firstObject];
                // 获取视频的 AVAsset
                [model requestAVAssetStartRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
                    // 开始下载iCloud上的视频
                } progressHandler:^(double progress, HXPhotoModel *model) {
                    // iCloud下载进度
                } success:^(AVAsset *avAsset, AVAudioMix *audioMix, HXPhotoModel *model, NSDictionary *info) {
                    // 获取成功
                    NSData *data = [NSData dataWithContentsOfURL:model.fileURL];
                    if (model.videoDuration < 30) {
                        [[UIApplication sharedApplication].keyWindow makeToast:@"视频时间不能小于30秒" duration:1.5 position:CSToastPositionCenter];
                        return;
                    }
                    NSLog(@"url - %@",model.fileURL);
                    UIImage *fengmian = [weakself getVideoPreViewImage:model.fileURL];
                    [weakself.selVideoBtn setImage:fengmian forState:UIControlStateNormal];
                    weakself.bofanImg.hidden = NO;
                    
                    [weakself updateVideoWithData:data];
                } failed:^(NSDictionary *info, HXPhotoModel *model) {
                    // 获取失败
                    [[UIApplication sharedApplication].keyWindow makeToast:@"获取视频失败" duration:1.5 position:CSToastPositionCenter];
                }];
            }
            
        } cancel:^(UIViewController *viewController, HXPhotoManager *manager) {
            [UINavigationBar appearance].translucent = NO;
            NSLog(@"block - 取消了");
        }];
    })
    .LeeAction(@"录制", ^{        //添加一个默认类型的Action (默认样式 字体颜色为蓝色)
        // 点击事件Block
        JCVideoRecordView *recordView = [[JCVideoRecordView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        recordView.cancelBlock = ^{
            
        };
        recordView.completionBlock = ^(NSURL *fileUrl) {
            AVURLAsset * asset = [AVURLAsset assetWithURL:fileUrl];
            CMTime   time = [asset duration];
            int seconds = ceil(time.value/time.timescale);
            if (seconds < 30) {
                [[UIApplication sharedApplication].keyWindow makeToast:@"视频时间不能小于30秒" duration:1.5 position:CSToastPositionCenter];
                return;
            }
            NSLog(@"url - %@",fileUrl);
            UIImage *fengmian = [weakself getVideoPreViewImage:fileUrl];
            [weakself.selVideoBtn setImage:fengmian forState:UIControlStateNormal];
            weakself.bofanImg.hidden = NO;
            NSData *data = [NSData dataWithContentsOfURL:fileUrl];
            NSLog(@"data -  %lu",(unsigned long)data.length);
            [weakself updateVideoWithData:data];
        };
        [recordView present];
    })
    .LeeCancelAction(@"取消", ^{    // 添加一个取消类型的Action (默认样式 alert中为粗体 actionsheet中为最下方独立)
        // 点击事件Block
    })
    .LeeShow();
}

- (void)updateVideoWithData:(NSData *)data{
    //将图片上传到服务器
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLoding];
    NSString *str = @"file";
    NSString *urlString = [User_HOST stringByAppendingString:str];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    if ([YLUserInfo isLogIn]) {
        [manager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"target"] = @2;
    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageDatas = data;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.mp4", str];
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageDatas
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"video/mpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"responseObject--- %@",responseObject);
        //上传成功
        if ([responseObject[Response_code] integerValue] == Response_value) {
            if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                NSArray *data = responseObject[@"data"];
                if (data.count > 0) {
                    NSDictionary *dic = [data firstObject];
                    weakself.videoFullPath = dic[@"path"];
                }
            }
        }else{
            [self.view makeToast:responseObject[@"returnMessage"] duration:1.5 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error -- %@",error);
        [EasyShowLodingView hidenLoding];
        //上传失败
        [self.view makeToast:@"上传失败" duration:1.5 position:CSToastPositionCenter];
    }];
}

// 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = 0.0;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
    
    return thumbnailImage;
}


- (HXPhotoManager *)manager
{
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.deleteTemporaryPhoto = NO;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.creationDateSort = YES;
        _manager.configuration.supportRotation = NO;
        _manager.configuration.cameraCellShowPreview = NO;
        _manager.configuration.navBarBackgroudColor = [UIColor whiteColor];
        _manager.configuration.navigationTitleColor = [UIColor blackColor];
        
        _manager.configuration.originalNormalImageName = @"zpgl_fb_wxz";
        _manager.configuration.originalSelectedImageName = @"zpgl_fb_xz";
        
        _manager.configuration.navigationBar = ^(UINavigationBar *navigationBar, UIViewController *viewController) {
            [navigationBar setBackgroundImage:[UIImage imageNamed:@"APPCityPlayer_bannerGame"] forBarMetrics:UIBarMetricsDefault];
            navigationBar.barTintColor = [UIColor whiteColor];
            navigationBar.tintColor = [UIColor blackColor];
        };
        //        _manager.configuration.sectionHeaderTranslucent = NO;
        //                _manager.configuration.navBarBackgroudColor = [UIColor redColor];
        //        _manager.configuration.sectionHeaderSuspensionBgColor = [UIColor redColor];
        //        _manager.configuration.sectionHeaderSuspensionTitleColor = [UIColor whiteColor];
        //        _manager.configuration.statusBarStyle = UIStatusBarStyleLightContent;
        //        _manager.configuration.selectedTitleColor = [UIColor redColor];
        
        //        _manager.configuration.requestImageAfterFinishingSelection = YES;
        
        __weak typeof(self) weakSelf = self;
        _manager.configuration.photoListBottomView = ^(HXDatePhotoBottomView *bottomView) {
        };
        _manager.configuration.previewBottomView = ^(HXDatePhotoPreviewBottomView *bottomView) {
        };
        _manager.configuration.albumListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"albumList:%@",collectionView);
        };
        _manager.configuration.photoListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"photoList:%@",collectionView);
        };
        _manager.configuration.previewCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"preview:%@",collectionView);
        };
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        
        // 使用自动的相机  这里拿系统相机做示例
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
        //        _manager.shouldSelectModel = ^NSString *(HXPhotoModel *model) {
        //            // 如果return nil 则会走默认的判断是否达到最大值
        //            //return nil;
        //            return @"Demo1 116 - 120 行注释掉就能选啦~\(≧▽≦)/~";
        //        };
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.photoCanEdit = YES;
    }
    return _manager;
}

- (NSMutableArray *)categaryArr{
    if (!_categaryArr) {
        _categaryArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _categaryArr;
}

@end
